import {Global, Module, Logger} from '@nestjs/common';
import {ConfigModule} from "../../../config/config.module";
import {ConfigService} from "../../../config/config.service";
import {TypeOrmModule,TypeOrmModuleAsyncOptions } from "@nestjs/typeorm";
import {ConfigOption} from "./mongo.dto";


export class MongoModule {
    static forRootAsync(option?: ConfigOption ){
        return TypeOrmModule.forRootAsync(
            {
                imports: [ConfigModule],
                useFactory: (configService:ConfigService) => {
                    let config:any =  {
                        type: 'mongodb',
                        host: configService.get('MONGODB_DATABASE_HOST'),
                        port: configService.get('MONGODB_DATABASE_PORT'),
                        username: configService.get('MONGODB_DATABASE_USER'),
                        password: configService.get('MONGODB_DATABASE_PWD'),
                        database: configService.get('MONGODB_DATABASE_DB'),
                        entities: [__dirname + '/**/*.entity.ts'],
                        synchronize: true,
                        retryAttempts: 20,
                        retryDelay: 4000,
                        autoLoadEntities: true, // 自动加载实体
                        keepConnectionAlive: false,
                        useUnifiedTopology: true,
                        ...option
                    };
                    Logger.log(config,'MongoModule');
                    return (
                        config
                    )
                },
                inject: [ConfigService]
            });
    }
    static forRoot(option?: ConfigOption ){
        return TypeOrmModule.forRoot({
                        type: 'mongodb',
                        host: "127.0.0.1",
                        port: 27017,
                        username: "root",
                        password: "123456",
                        database: "test",
                        entities: [__dirname + '/entity/mongo/**/*.entity.ts'],
                        synchronize: true,
                        retryAttempts: 20,
                        retryDelay: 4000,
                        autoLoadEntities: true, // 自动加载实体
                        keepConnectionAlive: false,
                        useUnifiedTopology: true,
                        ...option
                    });
    }
    static forFeature(entities: any, connection:string ){
        return TypeOrmModule.forFeature(entities, connection);
    }
}
